<template>
  <div class="user-management">
    <el-card>
      <div slot="header" class="clearfix" style="display: flex; align-items: center; justify-content: center;">
        <el-input v-model="searchKeyword" placeholder="请输入用户名/邮箱/电话" style="width: 200px;"
          @keyup.enter="search"></el-input>
        <el-button style="margin-left: 5px;" type="primary" icon="el-icon-search" @click="search"></el-button>
        <span style="position: absolute;">用户管理</span>
        <el-button style="margin-left: auto; padding: 3px 0" type="text" @click="showAddDialog">添加用户</el-button>
      </div>
      <el-table :data="users" style="width: 100%">
        <el-table-column label="用户头像" width="120">
          <template slot-scope="scope">
            <el-image style="width: 80px; height: 80px" :src="baseUrl + scope.row.avatarUrl"
              :preview-src-list="[baseUrl + scope.row.avatarUrl]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column label="性别" width="100">
          <template slot-scope="scope">
            {{ scope.row.gender === 'male' ? '男' : scope.row.gender === 'female' ? '女' : '其他' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="warning" @click="handleResetPassword(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.current"
        :page-sizes="[5, 10, 20, 50]" :page-size="page.size" layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="currentUser" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="currentUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="currentUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :on-change="handleAvatarChange"
            :auto-upload="false">
            <img style="width: 200px; height: 200px" v-if="currentUser.avatarUrl" :src="baseUrl + currentUser.avatarUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentUser.gender" placeholder="请选择性别">
            <el-option label="男" value="male"></el-option>
            <el-option label="女" value="female"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="currentUser.birthday"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import base from '@/utils/base.js';
export default {
  data() {
    return {
      baseUrl: base.url,
      users: [],
      searchKeyword: '',
      page: {
        current: 1,
        size: 5,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '',
      currentUser: {
        username: '',
        email: '',
        phone: '',
        avatarUrl: '',
        gender: '',
        birthday: ''
      },
      isEdit: false,
      isAdd: false,

    }
  },
  methods: {
    //处理上传头像
    handleAvatarChange(file) {
      // 处理文件上传逻辑，例如上传到服务器或本地存储
      console.log('待上传图:', file);
      this.currentUser.avatarUrl = file.name; // 假设上传成功后返回文件名 
      const formData = new FormData();
      formData.append('file', file.raw);
      console.log('当前头像:', this.currentUser.avatarUrl);
      this.$http.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response && response.code === 200) {
          this.currentUser.avatarUrl = response.url;
          console.log('上传头像图片成功:', response.url);
          this.$message.success('头像上传成功');
        } else {
          this.$message.error(response.message || '头像上传失败');
        }
      }).catch(error => {
        console.error('上传头像图片失败:', error);
        this.$message.error('上传头像失败: ' + (error.message || '未知错误'));
      });
    },
  //获取用户总数
  loadTotal(isSearch) {
      const apiUrl = isSearch ? '/admin/searchUserCount' : '/admin/userCount';
      this.$http.get(apiUrl, {
        params: {
          keyword: this.searchKeyword
        }
      }).then(response => {
        if (response && response.code === 200) {
          this.page.total = response.count;
        }
      }).catch(error => {
        console.error('获取用户总数失败:', error);
        this.$message.error('获取用户总数失败: ' + (error.message || '未知错误'));
      });
    },
//更新数据
    fetchUsers() {
      // TODO: 调用API获取用户列表
      console.log('searchKeyword:', this.searchKeyword);
      console.log('当前页码:', this.page.current);
      const lastId = this.page.current > 1 ? (this.page.current - 1) * this.page.size + 1 : 1;
      const apiUrl = this.searchKeyword ? 'admin/searchUsers' : 'admin/users';
      this.$http.get(apiUrl, {
        params: {
          lastId: this.searchKeyword ? 1 : lastId,
          limit: this.page.size,
          keyword: this.searchKeyword
        } 
      }).then(response => {
        if (response && response.code === 200) {
          console.log('获取用户列表成功:', response.users);
          this.users = response.users; 
        } else if(response.count == 0) {
          this.users = [];
          this.page.total = 0
          this.$message('暂无结果');;
        } else {
          this.$message.error('获取用户列表失败:'+ (response.message || '未知错误'));
        }
      }).catch(error => {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败:'+ (error.message || '未知错误'));
        this.users = [];
        this.page.total = 0
      });
    },
    search() {
      // TODO: 调用搜索API
      this.page.current = 1;
      this.loadTotal(true);
      this.fetchUsers();
    },
    handleSizeChange(val) {
      this.page.size = val;
      this.fetchUsers();
    },
    handleCurrentChange(val) {
      this.page.current = val;
      this.fetchUsers();
    },
    showAddDialog() {
      this.dialogTitle = '添加用户';
      this.currentUser ={
        username: '',
        email: '',
        phone: '',
        avatarUrl: '',
        gender: '',
        birthday: ''
      },
      this.isEdit = false;
      this.isAdd = true;
      this.dialogVisible = true;
    },
    //编辑用户
    handleEdit(row) {
      this.dialogTitle = '编辑用户';
      this.currentUser = { ...row };
      this.isEdit = true;
      this.isAdd = false;
      this.dialogVisible = true;
    },

    //删除用户
    handleDelete(row) {
      this.$confirm('确认删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/admin/deleteUser/${row.userId}`).then(response => {
          if (response && response.code === 200) {
            this.$message({
              type: 'success',
              message: response.message || '删除成功'
            });
            this.fetchUsers();
            this.loadTotal();
          } else {
            this.$message.error(response.message || '删除失败');
          }
        }).catch(error => {
          console.error('删除用户失败:', error);
          this.$message.error('删除用户失败: ' + (error.message || '未知错误'));
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //重置密码
    handleResetPassword(row) {
      this.$confirm('确认重置该用户密码吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post(`/admin/resetPassword/${row.userId}`).then(response => {
          if (response && response.code === 200) {
            this.$message({
              type: 'success',
              message: response.message || '密码已重置'
            });
          } else {
            this.$message.error(response.message || '密码重置失败');
          }
        }).catch(error => {
          console.error('密码重置失败:', error);
          this.$message.error('密码重置失败: ' + (error.message || '未知错误'));
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消重置'
        });
      });
    },
    submitForm() {
      // TODO: 根据isEdit调用添加或更新API
      if (this.isAdd) {
       console.log('当前状态添加:', this.currentUser); 
      }
      if (this.isEdit) {
       console.log('当前状态编辑:', this.currentUser); 
      }
      if (this.isEdit||this.isAdd) {
        // TODO: 调用API更新用户信息  
        //待修改的用户信息
        let updateUser = { ...this.currentUser }
        const apiUrl = this.isAdd? '/admin/addUser' : '/admin/updateUser';
        this.$http.post(apiUrl, updateUser).then(response => {
          if (response && response.code === 200) {
            this.$message.success('更新用户信息成功');
            this.dialogVisible = false;
            if (this.isAdd) {
              this.page.current = Math.ceil((this.page.total + 1) / this.page.size);
              this.page.total += 1;
            }
            this.fetchUsers(); 
          } else {
            this.$message.error('更新用户信息失败:'+ (response.message || '未知错误'));
          }
        }).catch(error => {
          console.error('更新用户信息失败:', error);
          this.$message.error('更新用户信息失败:'+ (error.message || '未知错误'));
        });
      }else {
        this.dialogVisible = false;
       return; 
      }

      
    }
  },
  created() {
    this.loadTotal(); // 页面加载时加载用户总数
    this.fetchUsers();
  },
  watch: {
    searchKeyword(oldeval, newVal) {
      //监听searchKeyword变化
      console.log('searchKeyword变化旧:', oldeval);
      console.log('searchKeyword变化新:', newVal);
      if (!newVal) {
        this.page.current = 1;
      }
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.el-form-item__label {
  line-height: 32px;
  padding-right: 10px;
}

.avatar-uploader {
  margin-top: 10px;
}
</style>